<?php

namespace Organize\Controllers\Auth;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Organize\Controllers\BaseOrganizeController;
use Organize\Resources\LeaderResources;
use Platform\Models\Organize\Leader;
use Platform\Repository\Organize\LeaderRepository;
use Platform\System\Tools\ResultTool;

/**
 * 登陆管理
 * Class LoginController
 * @package Admin\Controllers\Auth
 */
class LoginController extends BaseOrganizeController
{

    protected $repository;

    /**
     * LoginController constructor.
     * @param LeaderRepository $leaderRepository
     */
    public function __construct(LeaderRepository $leaderRepository)
    {
        parent::__construct();
        $this->repository = $leaderRepository;
    }

    /**
     * 组织成员登陆
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function login(Request $request){
        $username = $request->username;
        $password = $request->password;
        $leader = $this->repository->getOneByUsername($username);
        if (!$leader){
            return myResult()->setCode(ResultTool::CODE_TARGET_WRONG,'组织成员不存在')->send();
        }
        if ($leader->state === Leader::$STATE_LOCK){
            return myResult()->setCode(ResultTool::CODE_TARGET_WRONG,'组织成员已被冻结')->send();
        }
        $check = Hash::check($password,$leader['password']);
        if ($check) {
            $token = auth($this->auth_type)->login($leader);
            $res = myResult()->setData($leader,LeaderResources::class)->setMate(withToken($token,$this->auth_type))->send();
            $leader->savePermissions();
            return $res;
        }else{
            return myResult()->setCode(ResultTool::CODE_TARGET_WRONG,'账号密码不正确')->send();
        }
    }

    /**
     * 组织成员退出登陆
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout(){
        $this->leader->delPermissions();
        auth($this->auth_type)->logout();
        return myResult()->setCode(ResultTool::CODE_SUCCESS,'退出成功')->send();
    }
}
